<?php
// 每天短信发送次数获取与添加, 包含IP，手机号

namespace App\Http\Models;

use Illuminate\Support\Facades\Redis;;

class VerifyCodeModel
{
	
	const VERIFY_CODE_KEY = 'verifycode:';
	const EXPIRES_TIME = '1800';
	

	// 生成code, 返回前端唯一码key
	public function create($type, $mobile)
	{
		$redis = Redis::connection('db_main');
		$code = build_activation_key_number();
		$key = md5($type.$mobile.$code);
		if($redis->setex(self::VERIFY_CODE_KEY . $type . ':' . $mobile, self::EXPIRES_TIME, $key.'|'.$code)) {
			return ['key' => $key, 'code' => $code];
		}
		return '';
	}

	// 获取唯一码
	public function get_key($type, $mobile)
	{
		$redis = Redis::connection('db_db_main_slave');
		$key = self::VERIFY_CODE_KEY . $type .':'. $mobile;
		$value = $redis->get($key);
		if($value) {
			$pieces = explode('|', $value);
			$key = isset($pieces[0]) ? $pieces[0] : '';
			$code = isset($pieces[1]) ? $pieces[1] : '';
			return ['key'=>$key, 'code'=>$code];
		}
		return '';
	}

	// 验证
	public function verify($type, $mobile, $key, $code)
	{
		$redis = Redis::connection('db_main');
		$redis_key= self::VERIFY_CODE_KEY . $type . ':' . $mobile;
		$value = $redis->get($redis_key);
		if($value) {
			$pieces = explode('|', $value);
			$verify_key = isset($pieces[0]) ? $pieces[0] : '';
			$verify_code = isset($pieces[1]) ? $pieces[1] : '';
			if($key == $verify_key && $code == $verify_code){
				$redis->del($redis_key);
				return true;
			}
		}
		return false;
	}

}

